


#  https://github.com/wbt5/real-url
# new : https://github.com/rain-dl/real-url-proxy-server


# 获取斗鱼直播间的真实流媒体地址，默认最高画质
# 使用 https://github.com/wbt5/real-url/issues/185 中两位大佬@wjxgzz @4bbu6j5885o3gpv6ss8找到的的CDN，在此感谢！
import hashlib
import re
import time
import json


# pip3 install pyexecjs # quickjs : pip3 install quickjs
import execjs
import requests


ua="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"

class DouYu:
    """
    可用来替换返回链接中的主机部分
    两个阿里的CDN：
    dyscdnali1.douyucdn.cn
    dyscdnali3.douyucdn.cn
    墙外不用带尾巴的akm cdn：
    hls3-akm.douyucdn.cn
    hlsa-akm.douyucdn.cn
    hls1a-akm.douyucdn.cn
    """

    NAME="DouYu"

    def __init__(self, room_id):
        """
        房间号通常为1~8位纯数字，浏览器地址栏中看到的房间号不一定是真实rid.
        Args:
            roomid:
        """
        self.room_id=room_id

        self.timeout=(15,15)
        self.header=header = {
            'User-Agent': ua
        }

        self.did = '10000000000000000000000000001501'
        self.t10 = str(int(time.time()))
        # self.t13 = str(int((time.time() * 1000)))



    @staticmethod
    def md5(data):
        return hashlib.md5(data.encode('utf-8')).hexdigest()

    def get_pc_js(self, cdn='ws-h5', rate=0):
        """
        通过PC网页端的接口获取完整直播源。
        :param cdn: 主线路ws-h5、备用线路tct-h5
        :param rate: 1流畅；2高清；3超清；4蓝光4M；0蓝光8M或10M
        :return: JSON格式
        """

        with requests.Session() as session:
            t0=time.time()
            url='https://m.douyu.com/' + str(self.room_id)
            res = session.get(url, timeout=self.timeout)
            print("[info] =====>time used1:", round(time.time()-t0,4), url)

            res=res.text
            result = re.search(r'rid":(\d{1,8}),"vipId', res)

            if result:
                rid = result.group(1)
            else:
                raise Exception('房间号错误')
                return ""

            # 这步 耗时!!!
            t0=time.time()
            res = session.get('https://www.douyu.com/' + str(rid), timeout=self.timeout)
            print("[info] =====>time used2:", round(time.time()-t0,4))
            res=res.text
            # print('get_pc_js')
            # print(res)
            result = re.search(r'(vdwdae325w_64we[\s\S]*function ub98484234[\s\S]*?)function', res).group(1)
            func_ub9 = re.sub(r'eval.*?;}', 'strc;}', result)
            js = execjs.compile(func_ub9)
            res = js.call('ub98484234')

            v = re.search(r'v=(\d+)', res).group(1)
            rb = DouYu.md5(rid + self.did + self.t10 + v)

            func_sign = re.sub(r'return rt;}\);?', 'return rt;}', res)
            func_sign = func_sign.replace('(function (', 'function sign(')
            func_sign = func_sign.replace('CryptoJS.MD5(cb).toString()', '"' + rb + '"')

            js = execjs.compile(func_sign)
            params = js.call('sign', rid, self.did, self.t10)

            params += '&cdn={}&rate={}'.format(cdn, rate)
            url = 'https://www.douyu.com/lapi/live/getH5Play/{}'.format(rid)
            t0=time.time()
            res = session.post(url, params=params, timeout=self.timeout)
            res=res.json()
            print("[info] =====>time used3:", round(time.time()-t0,4))
            # return res
            try:
                live_url="%s/%s"%(res["data"]['rtmp_url'], res['data']['rtmp_live'])
            except Exception as e:
                print("[E]",e)
                live_url=""
            return live_url


    def get_live_url(self):
        #return self.get_pc_js(rate=3)
        # ->url,timeout
        return self.get_pc_js(rate=2),0


